package org.example.shoppingmall.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.shoppingmall.entity.Cart;
import org.example.shoppingmall.entity.Goods;
import org.example.shoppingmall.service.CartService;
import org.example.shoppingmall.service.impl.CartServiceImpl;
import org.example.shoppingmall.util.JsonUtils;
import org.example.shoppingmall.util.RedisUtil;
import org.example.shoppingmall.util.ResponseUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@WebServlet("/user/cart/*")
public class CartController extends HttpServlet {
    CartService cartService = new CartServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        switch (uri){
            case "/user/cart/getCart" ->{
                doGoodsDisplayInCart(req,resp);
            }
            default -> {

            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        switch (uri){
            case "/user/cart/del" -> {
                doGoodsDelete(req,resp);
            }
            case "/user/cart/update" -> {
                doCartUpdate(req,resp);
            }
            case "/user/cart/settlement" -> {
                doSettleIntoOrder(req,resp);
            }
            default -> {

            }
        }
    }

    /**
     * 删除购物车里已选商品
     * @param req
     * @param resp
     */
    private void doGoodsDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = null;
        String token = req.getHeader("Authorization");
        if (token != null) {
            if (token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
        }
        Integer user_id = Integer.parseInt(userId);

        JSONObject json = JsonUtils.getJson(req);
        Integer goods_id = json.getInteger("goods_id");

        boolean success = cartService.goodsDelete(goods_id,user_id);

        if(success){
            ResponseUtil.genSuccessResponse(resp,"删除成功",null);
        }else{
            ResponseUtil.gen404Response(resp,"删除失败");
        }
    }

    /**
     * 修改购物车内某商品购买数量
     * @param req
     * @param resp
     */
    private void doCartUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = null;
        String token = req.getHeader("Authorization");
        if (token != null) {
            if (token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
        }
        Integer user_id = Integer.parseInt(userId);

        JSONObject json = JsonUtils.getJson(req);
        Integer goods_id = json.getInteger("goods_id");
        Integer quantity = json.getInteger("quantity");

        boolean success = cartService.cartUpdate(goods_id,quantity,user_id);
        if(quantity <= 0){
            ResponseUtil.gen500Response(resp,"购买数量应大于0");
            return;
        }

            if(success){
                ResponseUtil.genSuccessResponse(resp,"修改成功",null);
            }else{
                ResponseUtil.gen404Response(resp,"修改失败");
            }
    }

    /**
     * 商品展示
     *
     * @param req  HttpServletRequest 对象
     * @param resp HttpServletResponse 对象
     * @throws IOException 如果响应发送失败
     */

    private void doGoodsDisplayInCart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = null;
        String token = req.getHeader("Authorization");
        if (token != null) {
            if (token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
        }
        Integer user_id = Integer.parseInt(userId);

        JSONObject json = JsonUtils.getJson(req);
        List<Goods> goodsList = null;
        Integer count;
        Integer page_size = json.getInteger("page_size");
        Integer page = json.getInteger("page");

        try {
            goodsList = cartService.goodsSearchInCart(page_size,page,user_id);
            count = cartService.goodsCountInCart(user_id);
            if (goodsList == null || goodsList.isEmpty() || count==null) {
                ResponseUtil.gen404Response(resp, "没有找到商品");
            } else {
                ResponseUtil.genCountAndListResponce(resp,"商品列表及总数返回成功",count,goodsList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.gen500Response(resp, "获取商品列表失败");
        }
    }

    /**
     * 将购物车结算成订单
     * @param req
     * @param resp
     * @return
     */
    public void doSettleIntoOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userId = null;
        String token = req.getHeader("Authorization");
        if (token != null) {
            if (token.startsWith("Bearer "))
                token = token.substring(7);
            userId = RedisUtil.get(token);
        }
        Integer user_id = Integer.parseInt(userId);

        JSONObject json = JsonUtils.getJson(req);
        List<Integer> goodsIdList = json.getJSONArray("goods_id").toJavaList(Integer .class);
        String address = json.getString("address");
        String phone = json.getString("phone");

        //判空
        if(goodsIdList==null || address == null || phone == null || address.isEmpty() || address.isEmpty() || goodsIdList.isEmpty()){
            ResponseUtil.gen500Response(resp,"已选商品列表和收货地址和手机号不能为空");
            return;
        }

        //获取购物车
        List<Cart> cartList = cartService.getInfoFromCart(goodsIdList);


        //二重判断
        boolean isMoneyEnough = cartService.moneyJudging(goodsIdList,user_id);
        boolean isStockEnough = cartService.quantityJudging(goodsIdList,user_id);
        if(!isMoneyEnough){
            ResponseUtil.gen404Response(resp,"账户余额不足");
            return;
        }
        if(!isStockEnough){
            ResponseUtil.gen404Response(resp,"商品库存不足");
            return;
        }
        //结算
        if(isStockEnough&&isMoneyEnough){
            List<Integer> stockList = cartService.stockCalculate(goodsIdList,user_id);
            BigDecimal balance = cartService.balanceCalculate(goodsIdList,user_id);
            boolean moneySuccess = cartService.reduceBalance(user_id,balance);
            boolean stockSuccess = cartService.updateStock(goodsIdList,stockList);
            boolean orderSuccess = cartService.settleIntoOrder(address,phone,cartList);
            if (stockSuccess && moneySuccess && orderSuccess){
                ResponseUtil.genSuccessResponse(resp,"结算成功，订单已生成","账户余额："+ balance);
            }else{
                ResponseUtil.gen404Response(resp,"结算失败，订单未生成");
            }
        }

    }
}
